<template>
	<view class="content">
    <view class="header">
    	<image src="/static/images/login/logo.ico"></image>
    </view>
    
    <!-- #ifndef MP -->
    <!-- 非微信小程序 -->
    <view class="list">
    	<view class="list-call">
    		<input class="sl-input" v-model="state.login.username" type="text" maxlength="11" placeholder="输入账号" />
    	</view>
    	<view class="list-call">
    		<input class="sl-input" v-model="state.login.password" type="text" maxlength="32" placeholder="输入密码"
    			password="true" />
    	</view>
    
    </view>
    
    <view class="button-login" hover-class="button-hover" @click="bindLogin()">
    	<text>登录</text>
    </view>
    <view style="margin: 80rpx auto 30rpx; color: #8B8982; text-align: center;">未注册？<br/>请登录微信小程序授权登录注册</view>
    <!-- #endif -->


    <!-- #ifdef MP -->
    <!-- 仅在微信小程序中 -->
    <view class="agreenment" @click="openReg">
    	<uv-icon name="weixin-fill" color="#2979ff" size="40"></uv-icon>
    	<!-- <navigator url="/pages/login/reg" open-type="navigate">微信授权注册</navigator> -->
    	<uv-text text="微信一键注册登录"></uv-text>
    </view>
    <!-- 注册抽屉 -->
    <view>
    	<!-- <uv-popup ref="popup" @change="change"> -->
    	<uv-popup ref="popup">
    		<view>
    			<uv-form labelPosition="left" :model="modelReg">
    				<uv-form-item label="昵称" prop="nickname" borderBottom>
    					<uv-input v-model="modelReg.nickname" type="nickname" border="none">
    						<!-- <uv-input v-model="modelReg.nickname" type="text" border="none"> -->
    					</uv-input>
    				</uv-form-item>
    				<uv-form-item label="头像" prop="avatar" borderBottom>
    					<uv-button open-type="chooseAvatar" @chooseavatar="wxGetAvatar">
    						<uv-image :src="modelReg.avatar" shape="circle" class="avatarContainer"></uv-image>
    					</uv-button>
    				</uv-form-item>
    				<uv-button type="primary" @click="wxAuth">授权注册</uv-button>
    			</uv-form>
    
    		</view>
    	</uv-popup>
    	<!-- <button @click="open">打开</button> -->
    </view>
    <!-- #endif -->

	</view>
</template>

<script setup>
	import {
		callWithErrorHandling,
		reactive,
		ref
	} from 'vue';
	import nx from '@/nx';
	import {onLoad} from '@dcloudio/uni-app'
	import { baseUrl } from '@/nx/config'
  // 非微信页面登录
	const state = reactive({
		login: {
			username: '',
			password: ''
		}
	});
	const modelReg = ref({
		wx_openId: "",
		// username: "",
		nickname: "",
		// password: "default123",
		// repassword: "default123",
		avatar: "https://cdn.uviewui.com/uview/album/1.jpg"
	})
	const popup = ref(null)
	// const userOpenid = ref("")
	let userOpenid = ""
  let wxLoginState = {}
	
	const getOpenid = () => {
		uni.login({
			provider: 'weixin',
			success: async (loginRes) => {
				let resp = await nx.$api.wxTools.jscode2Session({
					code: loginRes.code
				})
				// userOpenid.value = resp.data.openid
				userOpenid = resp.data.openid
        wxLoginState.wx_openId = userOpenid
			}
		})
	}
  
  const wxLogin = async (data) => {
    // 向服务器发送登录请求，这里只是校验了是否存在这个用户
    let resp = await nx.$api.user.wxAccountLogin(data)
    if (resp.code === 200){
      // 存在该用户，直接跳转首页实现一键登陆
      console.log("登录中，调用setToken")
      // 设置token
      nx.$store('user').setToken(resp.data)
      // 获取用户信息，header中有authorization信息
      await nx.$store('user').getInfo()
      // console.log('翻页前的返回值',resp);
      // 获取后进入首页
      uni.switchTab({
      	url: '/pages/index/index'
      })
      return 200  // 也就是都完成了
    }else{
      return resp.code  // 第一步就没有用户存在
    }
  }
	// 启动时获取用户openid
	onLoad(()=>{
    // #ifdef MP
    getOpenid()
    console.log('页面onload',wxLoginState);
    // #endif
	})

	const openReg = async () => {
    // 用户存在就是true，不存在就是false
    const loginCode = await wxLogin(wxLoginState)
    // console.log("返回值", loginCode);
    if (loginCode === 400) {
      // 针对用户不存在的情况
      modelReg.value.nickname=""
      modelReg.value.avatar="https://cdn.uviewui.com/uview/album/1.jpg"
      popup.value.open('top')
    }
	}


	const wxGetAvatar = (e) => {
		// console.log("获取头像", e);
		// modelReg.value.avatar = e.avatarUrl
		// 上传图片至服务器
		uni.uploadFile({
			url:baseUrl+'/tool/img',
			name: 'file',
			filePath:e.avatarUrl,
			success: (res) => {
				const imgData = JSON.parse(res.data)  //要JSON.parse，否则返回的是一个字符串
				modelReg.value.avatar = imgData.data.url
			}
		})
	}
	const wxAuth = async () => {
		modelReg.value.wx_openId = userOpenid
		// 注册用户
		let resp = await nx.$api.user.userRegister(modelReg.value)
		if(resp.code===200){
      // 注册完后自动登录
      const loginCode = await wxLogin(wxLoginState)

		}
	}

	function bindLogin() {
		// if (state.login.phone.length != 11) {
		// 	uni.showToast({
		// 		icon: 'none',
		// 		title: '手机号不正确'
		// 	});
		// 	return;
		// }
		// if (state.login.password.length < 6) {
		// 	uni.showToast({
		// 		icon: 'none',
		// 		title: '密码不正确'
		// 	});
		// 	return;
		// }
		// 提交数据
		console.log("登录", state.login);
		nx.$api.user.accountLogin(state.login).then((res) => {
			if (res.code === 200) {
				uni.showToast({
					title: '登录成功！',
					icon: 'none'
				});
        // 设置token
        console.log("登录后", res.data);
        nx.$store('user').setToken(res.data)
        
        // 获取用户信息，header中有authorization信息
        nx.$store('user').getInfo()
				// 跳转首页
				uni.switchTab({
					url: '/pages/index/index'
				})
			} else {
				console.log(res);
			}
		}).catch(err => {
			console.log(err);
		});
	}
</script>

<style lang='scss' scoped>
	page {
		background-color: #fff;
	}

	.content {
		display: flex;
		flex-direction: column;
		justify-content: center;
	}

	.header {
		width: 161rpx;
		height: 161rpx;
		border-radius: 50%;
		margin-top: 30rpx;
		margin-left: auto;
		margin-right: auto;
	}

	.header image {
		width: 161rpx;
		height: 161rpx;
		border-radius: 50%;
	}

	.list {
		display: flex;
		flex-direction: column;
		padding-top: 50rpx;
		padding-left: 70rpx;
		padding-right: 70rpx;
	}

	.list-call {
		display: flex;
		flex-direction: row;
		justify-content: space-between;
		align-items: center;
		height: 100rpx;
		color: #333333;
		border-bottom: 0.5px solid #e2e2e2;
	}



	.list-call .sl-input {
		flex: 1;
		text-align: left;
		font-size: 32rpx;
		margin-left: 16rpx;
	}

	.button-login {
		color: #FFFFFF;
		font-size: 34rpx;
		width: 470rpx;
		height: 100rpx;
		background: linear-gradient(-90deg, rgba(0, 103, 171, 1), rgba(0, 71, 119, 1));
		border-radius: 50rpx;
		line-height: 100rpx;
		text-align: center;
		margin-left: auto;
		margin-right: auto;
		margin-top: 100rpx;
	}

	.button-hover {
		background: linear-gradient(-90deg, rgba(0, 103, 171, 0.8), rgba(0, 71, 119, 0.8));
	}

	.agreenment {
/* 		display: flex;
		flex-direction: row;
		justify-content: center;
		align-items: center; */
		margin: 80rpx auto 30rpx;
		color: #8B8982;
		height: 40rpx;
		line-height: 40rpx;
    uv-icon {
      margin-bottom: 180rpx;
    }
	}

	/* 	.agreenment text {
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 24rpx;
		margin-left: 15rpx;
		margin-right: 15rpx;
	} */
</style>